#include <iostream>
#include <string>

#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>

#include "Client.h"
#include "Protocol.h"
#include "CharacterClient.h"
#include "KeyBoardAction.h"
#include "MonsterClient.h"
#include "GemClient.h"
#include "ScoreClient.h"
#include "Message.h"

using namespace std;

Client::Client(int* resolution, string windowName) {
	threadPrincipal = new sf::Thread(&Client::drawEngine, this);
	window = new sf::RenderWindow(sf::VideoMode(resolution[0],resolution[1]), windowName);
}

int Client::socketCreation(string address, int port) {
	sf::Socket::Status status = socket.connect(address, 53000);
	if (status != sf::Socket::Done) {
		cout << "Error : connection keyboard failed to Server" << endl;
		return -1;
	}

	char color[1];
	size_t received;

	socket.receive(color, 1, received);

	if(color[0] == 'r') {
		cout << "Joueur 1 : " << color[0] << endl;
		characterClient = new CharacterClient(sf::Color::Red);
		otherCharacterClient = new CharacterClient(sf::Color::Blue);
	} else if (color[0] == 'b') {
		cout << "Joueur 2 : " << color[0] << endl;
		characterClient = new CharacterClient(sf::Color::Blue);
		otherCharacterClient = new CharacterClient(sf::Color::Red);
	}


	return 0;

}

int Client::launchGame() {

	partySart = true;
	bool gameEnded = false;
	sf::Clock clock;

	cout << "Client : Lancement d'une partie de jeu" << endl;

	Keyboard_Action move;

	sf::Event event;
	// run the program as long as the window is open
	while (window->isOpen()) {
		sf::Time elapsed = clock.restart();
		while (window->pollEvent(event) && !gameEnded) {
			//printf("Event : %d\n", event.key.code);
			/*Touche clavier appuye*/
			if (event.type == sf::Event::KeyPressed /*|| 
				event.type == sf::Event::JoystickMoved || event.type == sf::Event::JoystickButtonPressed*/) {

				/*if (event.type == sf::Event::JoystickButtonPressed) {
					printf("type : %d\n", event.joystickButton.button);
				}*/
				if (event.key.code == sf::Keyboard::Escape)
					window->close();

				/*Deplacement a gauche*/
				if (characterClient->chAction != DEAD) {
					if ((event.key.code == sf::Keyboard::Left /*|| (event.type == sf::Event::JoystickMoved && event.joystickMove.axis == sf::Joystick::PovX && event.joystickMove.position < -70)*/
						&& ((characterClient->chAction == FACING || characterClient->chAction == JUMPING) || characterClient->chDirection == RIGHT))) {
						move = MOVE_LEFT_PRESS;

						if (socket.send(&move, sizeof(Keyboard_Action)) != sf::Socket::Done) {
							cout << "Error :Client send failed Keyboard Pressed" << endl;
							return 1;
						}				
					/*Deplacement a droite*/
					} else if (event.key.code == sf::Keyboard::Right /*|| (event.type == sf::Event::JoystickMoved && event.joystickMove.axis == sf::Joystick::PovX && event.joystickMove.position > 70)*/
						&& ((characterClient->chAction == FACING || characterClient->chAction == JUMPING) || characterClient->chDirection == LEFT)) {
						move = MOVE_RIGHT_PRESS;

						if (socket.send(&move, sizeof(Keyboard_Action)) != sf::Socket::Done) {
							cout << "Error :Client send failed Keyboard Pressed" << endl;
							return 1;
						}			
					}
					/*Action de saut*/
					if (event.key.code == sf::Keyboard::Space /*|| (event.type == sf::Event::JoystickButtonPressed)*/
						&& !(characterClient->chAction == JUMPING || characterClient->chAction == JUMPRUNNING )) {
						move = JUMP_PRESS;

						if (socket.send(&move, sizeof(Keyboard_Action)) != sf::Socket::Done) {
							cout << "Error: Client send failed Spacebar Pressed" << endl;
							return 1;
						}
					}
				}
			}

			/*Touche clavier relachee*/
			if (event.type == sf::Event::KeyReleased /*|| event.type == sf::Event::JoystickMoved*/) {
				if(event.key.code == sf::Keyboard::Left 
					/*|| (event.type == sf::Event::JoystickMoved && event.joystickMove.axis == sf::Joystick::X && 
						event.joystickMove.position > 0 && event.joystickMove.position < 70)*/) {
					move = MOVE_LEFT_REL;
					if (socket.send(&move, sizeof(Keyboard_Action)) != sf::Socket::Done) {
						cout << "Error : Client send failed Keyboard Released " << endl;
						return 1;
					}
				} else if (event.key.code == sf::Keyboard::Right
					/*|| (event.type == sf::Event::JoystickMoved && event.joystickMove.axis == sf::Joystick::X && 
						event.joystickMove.position > -70 && event.joystickMove.position < 0)*/) {
					move = MOVE_RIGHT_REL;
					if (socket.send(&move, sizeof(Keyboard_Action)) != sf::Socket::Done) {
						cout << "Error : Client send failed Keyboard Released " << endl;
						return 1;
					}
				}
			}

			// "close requested" event: we close the window
			if (event.type == sf::Event::Closed)
				window->close();	

		}

		sf::Time sleepTime = sf::seconds(1.0f/60.0f) - clock.getElapsedTime();
		if (sleepTime.asSeconds() > 0.0f) {
			sf::sleep(sleepTime);
		}
	}

	return 0;
}

void Client::drawEngine() {
	MonsterClient* monster = new MonsterClient();
	//GemClient* yellowGem = new GemClient(GemColour::YELLOW);
	score = new ScoreClient();

	cwo = new ClientWorldObjects(&socket);

	sf::Texture texture;
	if (!texture.loadFromFile("../Img/maps/levelDemo.png")) {
		printf("Background image not found\n");
	}

	background.setTexture(texture);

	Message* msg = new Message;

	while(partySart = true) {
		characterClient->animationPlayer1();
		otherCharacterClient->animationPlayer1();
		monster->animationMonster();
		cwo->animationObjects();

		window->clear(sf::Color::White);
		window->draw(background);

		characterClient->receive(socket);
		score->setScore(characterClient->nbPoints);
		otherCharacterClient->receive(socket);
		monster->receive(socket);
		//yellowGem->receive(socket);
		cwo->receive();

		characterClient->draw(*window);
		otherCharacterClient->draw(*window);
		monster->draw(*window);
		//yellowGem->draw(*window);
		cwo->draw(*window);
		score->drawScore(*window);
		if (characterClient->hasWon()) {
			msg->drawYouWin(*window);
		} else if (otherCharacterClient->hasWon()) {
			msg->drawOtherWin(*window);
		} else if (characterClient->chAction == DEAD && otherCharacterClient->chAction == DEAD) {
			msg->drawYouLoose(*window);
		}

		window->display();
		
	}

}


/*int Client::startAmbiantMusic() {
	if (!ambiantMusic.openFromFile("../Music/Bob's Adventures - back34.mp3")) {
		return -1; // erreur
	}

	ambiantMusic.play();

	return 0;
}

void Client::stopAmbiantMusic() {
	ambiantMusic.stop();
}

void Client::playBounceSound() {

}*/
